package edu.uwaterloo.bicycle.framework;

import edu.uwaterloo.bicycle.framework.ShapedFrameUtils.Result;

import java.awt.Graphics;

import javax.swing.BorderFactory;
import javax.swing.JButton;

public class ShapedButton extends JButton {
  private static final long serialVersionUID = 1L;
  final Result result;

  public ShapedButton(String imgName) throws Exception {
    this.result = ShapedFrameUtils.restore(imgName);
    this.setOpaque(false);
    this.setFocusPainted(false);
    this.setBorderPainted(false);
    this.setContentAreaFilled(false);
    this.setBorder(BorderFactory.createEmptyBorder(0, 0, this.result.size.width, this.result.size.height));
    this.setSize(this.result.size);
    this.setMinimumSize(this.result.size);
    this.setMaximumSize(this.result.size);
  }

  @Override
  public boolean contains(final int x, final int y) {
    if ((this.result.shape == null) || !this.result.shape.getBounds().equals(this.getBounds())) {
      return this.result.shape.contains(x, y);
    }
    return super.contains(x, y);
  }

  @Override
  public void paintComponent(final Graphics g) {
    if ((ShapedButton.this.result != null) && (ShapedButton.this.result.image != null)) {
      g.drawImage(ShapedButton.this.result.image, 0, 0, null);
    } else {
      super.paintComponent(g);
    }
  }
}
